package com.faklyn.bootredis.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author huilin_rong
 * @date 2021/01/18
 */
@Slf4j
@RestController
public class RedissonController {

    @Resource
    private RedissonClient redissonClient;

    @GetMapping("testRedisson")
    public Object testRedisson(Integer id) {
        String productId = "product_249";
        RLock rLock = redissonClient.getLock(productId);
        boolean isLock = false;
        try {
            isLock = rLock.tryLock(15, TimeUnit.SECONDS);
            if (isLock) {
                log.info("{} 抢到了锁", id);
                Thread.sleep(5000);
            } else {
                log.info("{} 抢锁失败", id);
            }
        } catch (Exception e) {
            log.error("error:{}", e);
        } finally {
            if (isLock) {
                rLock.unlock();
            }
        }
        return "done";
    }


}
